<?php
/**
 * @Author: Marte
 * @Date:   2018-08-21 10:43:17
 * @Last Modified by:   Marte
 * @Last Modified time: 2018-08-21 15:16:07
 */

namespace app\wechat\service;
use think\Request;
class Wxuser
{
    /*微信回调获取用户信息
        @paramer  $redirect_url   回调网址
        @paramer  $scope          授权方式
        应用授权作用域，snsapi_base ，snsapi_userinfo （弹出授权页面，可通过openid拿到昵称、性别、所在地。并且，即使在未关注的情况下，只要用户授权，也能获取其信息）
        @paramer  $state          用户自己定义的参数
        return code
        回调 返回code 或 $state用户定义的参数
    */
    public function wei_get_acquire_code($redirect_uri,$scope='snsapi_userinfo',$state='ABCD'){
                $redirect_uri=urlencode($redirect_uri);
                $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('APPID').'&redirect_uri='.$redirect_uri.'&response_type=code&scope='.$scope.'&state='.$state.'&connect_redirect=1#wechat_redirect';
                header("Location:".$url);
    }

    // 获取网页授权的用户信息
    public function wei_get_info($code){
        //根据code获得Access Token
        $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.config('APPID').'&secret='.config('APPSECRET').'&code='.$code.'&grant_type=authorization_code';
        $access_token_json =$this->https_request($access_token_url);
        $access_token_array = json_decode($access_token_json,true);
        $openid = $access_token_array['openid'];
        $access_token = $access_token_array['access_token'];
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
        $output = $this->httpGet($url);
        $info = json_decode($output,true);
        return $info;
    }

    public function GetToken(){

    }

    //生成access_token
    public function getAccessToken() {
        if(cache('access_token')){
            $access_token=cache('access_token');
        }else{
            $access_token_url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.config('APPID').'&secret='.config('APPSECRET');
            $res = json_decode($this->httpGet($access_token_url),true);
            cache('access_token',$res['access_token'],7000);
            $access_token=cache('access_token');
        }
        return $access_token;
    }


    //获取用户分享配置
    public  function getSignPackage(){
            // 注意 URL 一定要动态获取，不能 hardcode.
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            $url = "$protocol".config('WxDomain')."$_SERVER[REQUEST_URI]";
            $appId = config('APPID');
            $jsapiticket = $this->getJsApiTicket();
            $timestamp = time();
            $nonceStr = $this->createNonceStr();
            // 这里参数的顺序要按照 key 值 ASCII 码升序排序
            $string = "jsapi_ticket=$jsapiticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
            $signature = sha1($string);
            $signPackage = array(
                "appId"     => $appId,
                "nonceStr"  => $nonceStr,
                "timestamp" => $timestamp,
                "url"       => $url,
                "signature" => $signature,
                "rawString" => $string
            );
            return $signPackage;
        }

    public function createNonceStr($length = 16) {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            $str = "";
            for ($i = 0; $i < $length; $i++) {
                $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
            }
            return $str;
        }

    public function getJsApiTicket() {
            if(cache('ticket')){
                $ticket=cache('ticket');
            }else{
                $accessToken = $this->getAccessToken();
                $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
                $res = json_decode($this->httpGet($url),true);
                cache('ticket',$res['ticket'],7000);
                $ticket=cache('ticket');
            }
            return $ticket;
    }

    // 小程序登录
    public function WechatXcxLogin(){
        $request = Request::instance();
        $APPID = config('XAPPID');
        $AppSecret = config('XAPPSECRET');
        $code = $request->post('code');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $APPID . "&secret=" . $AppSecret . "&js_code=" . $code . "&grant_type=authorization_code";
        $arr = $this->httpGet($url);
        $arr = json_decode($arr, true);
        $openid = $arr['openid'];
        $session_key = $arr['session_key'];
        // 数据签名校验
        $signature = $request->post('signature');
        $rawData = $request->post('rawData');
        $signature2 = sha1($rawData . $session_key);
        if ($signature != $signature2) {
            return false;
        }
        Vendor("PHP.wxBizDataCrypt");
        $encryptedData = $request->post('encryptedData');
        $iv = $request->post('iv');
        $pc = new \WXBizDataCrypt($APPID, $session_key);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        $data = json_decode($data,true);
        if ($errCode == 0) {
            return $data;
            die;
        } else {
            return false;
        }
    }

    public function https_request($url){
            $curl =curl_init();
            curl_setopt($curl,CURLOPT_URL,$url);
            curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
            curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);
            curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
            $data = curl_exec($curl);
            if(curl_errno($curl)){
                return 'ERROR '.curl_error($curl);
            }
            curl_close($curl);
            return $data;
    }

    public  function httpGet($url) {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_TIMEOUT, 500);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_URL, $url);
            $res = curl_exec($curl);
            curl_close($curl);
            return $res;
    }
}